package com.tzx.base.utils

import android.app.Activity
import android.app.Application.ActivityLifecycleCallbacks
import android.os.Bundle
import android.util.Log
import android.widget.Toast
import java.lang.ref.WeakReference
import kotlin.math.log

open class AppActivityLifecycleCallbacks : ActivityLifecycleCallbacks {
    override fun onActivityCreated(activity: Activity, savedInstanceState: Bundle?) {}

    override fun onActivityStarted(activity: Activity) {}

    override fun onActivityResumed(activity: Activity) {}

    override fun onActivityPaused(activity: Activity) {}

    override fun onActivityStopped(activity: Activity) {}

    override fun onActivitySaveInstanceState(activity: Activity, outState: Bundle) {}

    override fun onActivityDestroyed(activity: Activity) {}
}
interface AppGroundListener {
    fun onBackground()

    fun onForeground()
}

object AppGroundInstance : AppGroundListener {
    var isBackGround = false
    override fun onBackground() {
        Toast.makeText(AppHelper.application, "应用切换到后台", Toast.LENGTH_SHORT).show()
        isBackGround = true
    }

    override fun onForeground() {
        if (isBackGround) {
            Toast.makeText(AppHelper.application, "应用切换到前台", Toast.LENGTH_SHORT).show()
        }
        isBackGround = false
    }

}
object AppActivityLifecycleCallbackInstance : AppActivityLifecycleCallbacks() {
    private val activityLists:MutableList<WeakReference<Activity>> = mutableListOf()
    private var currentActivity: WeakReference<Activity>? = null
    private var activityResumedCount = 0
    override fun onActivityCreated(activity: Activity, savedInstanceState: Bundle?) {
        activityLists.add(WeakReference<Activity>(activity))
    }
    override fun onActivityResumed(activity: Activity) {
        currentActivity = WeakReference(activity)
        activityResumedCount++
        if (activityResumedCount == 1) {
            AppGroundInstance.onForeground()
        }
    }

    override fun onActivityStopped(activity: Activity) {
        super.onActivityStopped(activity)
        activityResumedCount--
        if (activityResumedCount == 0) {
            AppGroundInstance.onBackground()
        }
    }

    override fun onActivityDestroyed(activity: Activity) {
        activityLists.find { it.get() == activity }?.let { activityLists.remove(it) }
    }

    /**
     * 获取当前栈顶的Activity
     */
    fun getTopActivity(): Activity? = currentActivity?.get()

}